package com.example.smartall.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.smartall.R;
import com.example.smartall.adapter.PervasiveAdapter;
import com.example.smartall.api.Api;
import com.example.smartall.api.ApiConfig;
import com.example.smartall.api.NetCallBack;
import com.example.smartall.diaglog.LoadedDialog;
import com.example.smartall.entity.ActCommentBean;
import com.example.smartall.entity.ActDetailsBean;
import com.example.smartall.entity.ActListBean;
import com.example.smartall.ui.base.BaseActivity;
import com.example.smartall.utils.Constant;
import com.example.smartall.utils.SPUtils;
import com.example.smartall.view.SListView;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Author: abbas
 * @CreateDate: 2022/2/8
 * @Description: 详情页面顶部栏显示活动名称，点击“返回”按钮，返回上级目录。
 * ②活动详情内容按照（图片+文字）的形式进行展示，详情页面具有活动评论与查看功能，查看评论显示评论条数，以及列表形式展现的评论内容，还可以对该活动进行评论。
 * ③详情页面包括活动推荐，以列表形式展示1-3篇推荐活动。
 * ④活动页面包括报名按钮，点击加入该活动。
 * <p>
 * 大概意思是有俩Activity吧
 * 活动详情 --> 导航栏返回、评论、查看、评论条数、评论内容、推荐活动
 * 活动页面 --> 内容详情、报名
 */
public class ActDetailsActivity extends BaseActivity {

    //活动ID 由活动列表传递
    private int actId = -1;
    //评论总数
    private int commentTotal = -1;
    //分页页数
    private int pageNum = 1;
    //单页数量
    private int pageSize = 12;

    private ImageView img;
    private TextView tvName;
    private TextView tvContent;
    private Button btAct;
    private Button btComment;
    private SListView lvComment;
    private SListView lvRecommend;
    private EditText etComment;
    private ImageView imBack;
    private TextView tvTitle;

    private ActDetailsBean.DataBean detailsBean;
    private List<ActCommentBean.RowsBean> commentBeans = new ArrayList<>();
    private ActCommentAdapter adapter;
    private List<ActListBean.RowsBean> recommendActBeans = new ArrayList<>();
    private ActListAdapter recommendAdapter;

    private MHandler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_details);

        actId = getIntent().getIntExtra("id", actId);

        handler = new MHandler();

        init();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getDetails();
        getRecommendAct();
    }

    @Override
    public void init() {
        img = (ImageView) findViewById(R.id.img);
        tvName = (TextView) findViewById(R.id.tv_name);
        tvContent = (TextView) findViewById(R.id.tv_content);
        btAct = (Button) findViewById(R.id.bt_act);
        btComment = (Button) findViewById(R.id.bt_comment);
        lvComment = (SListView) findViewById(R.id.lv_comment);
        lvRecommend = (SListView) findViewById(R.id.lv_recommend);
        etComment = (EditText) findViewById(R.id.et_comment);
        imBack = (ImageView) findViewById(R.id.im_back);
        tvTitle = (TextView) findViewById(R.id.tv_title);

        tvTitle.setText("活动详情");
    }

    @Override
    public void initEvent() {
        imBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActDetailsActivity.this.finish();
            }
        });
        //查看活动
        btAct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ActDetailsActivity.this, ActContentActivity.class);
                intent.putExtra("data", detailsBean);
                startActivity(intent);
            }
        });
        //查看评论
        btComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (commentBeans.size() == commentTotal) {
                    showToast("已加载所有数据");
                    return;
                }
                getComment(pageNum);
                pageNum++;
            }
        });
        //发送评论
        etComment.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND) {
                    sendComment();
                }
                return false;
            }
        });
    }

    private void sendComment() {
        LoadedDialog dialog = new LoadedDialog(ActDetailsActivity.this);
        dialog.show();
        HashMap<String, Object> params = new HashMap<>();
        params.put("activityId", actId);
        params.put("content", etComment.getText().toString());
        Api.config(ApiConfig.ACT_SEND_COMMENT, params).postRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                if (res.contains("200")) {
                    showToastSync("评论成功");
                    commentBeans.clear();
                    pageNum = 1;
                    getComment(pageNum);
                } else {
                    showToastSync("评论失败，请检查网络");
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        }, SPUtils.config(ActDetailsActivity.this, Constant.SP_USER_FILE_NAME).getString(Constant.TOKEN));
    }

    private void getDetails() {
        LoadedDialog dialog = new LoadedDialog(ActDetailsActivity.this);
        dialog.show();
        Api.config(ApiConfig.ACT_DETAILS, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                ActDetailsBean bean = new Gson().fromJson(res, ActDetailsBean.class);
                if (bean != null && bean.getCode() == 200) {
                    detailsBean = bean.getData();
                    handler.sendEmptyMessage(0x01);
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        }, "" + actId);
    }

    private void getComment(int pageNum) {
        //妙啊 一不小心 上百条数据就炸了
        LoadedDialog dialog = new LoadedDialog(ActDetailsActivity.this);
        dialog.show();

        Api.config(ApiConfig.ACT_COMMENT, null).getRequest(ActDetailsActivity.this, new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                dialog.dismiss();
                ActCommentBean bean = new Gson().fromJson(res, ActCommentBean.class);
                if (bean != null && bean.getCode() == 200) {
                    commentBeans.addAll(bean.getRows());
                    handler.sendEmptyMessage(0x02);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btComment.setText("(评论条数：" + bean.getTotal() + ")当前条数：" + commentBeans.size() + " 点击加载更多");
                        }
                    });
                }
            }

            @Override
            public void onFailure(Exception e) {
                dialog.dismiss();
            }
        }, "?activityId=" + actId + "&pageNum=" + pageNum + "&pageSize=" + pageSize);
    }

    //获取推荐活动
    private void getRecommendAct() {
        if (recommendActBeans.size() > 0) return;
        Api.config(ApiConfig.ACT_LIST, null).getRequest(new NetCallBack() {
            @Override
            public void onSuccess(String res) {
                ActListBean bean = new Gson().fromJson(res, ActListBean.class);
                if (bean != null && bean.getCode() == 200) {
                    recommendActBeans = bean.getRows();
                    handler.sendEmptyMessage(0x03);
                }
            }

            @Override
            public void onFailure(Exception e) {

            }
        }, "?recommend=Y");
    }

    class MHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0x01:
                    Glide.with(ActDetailsActivity.this).load(ApiConfig.BASE_URL + detailsBean.getImgUrl()).into(img);
                    tvName.setText(detailsBean.getName());
                    tvContent.setText("报名人数：" + detailsBean.getSignupNum() +
                            "\n发布时间：" + detailsBean.getPublishTime());
                    break;
                case 0x02:
                    if (adapter == null) {
                        adapter = new ActCommentAdapter(commentBeans);
                        lvComment.setAdapter(adapter);
                    } else {
                        if (commentBeans == adapter.getData()) return;
                        adapter.setData(commentBeans);
                    }
                    //终于找到
//                    /profile/upload/2021/12/06/2d62fbb5-0704-413e-956a-256ddc586729.png
//                    /prod-api//profile/upload/2022/01/22/e399cdf5-66fa-4c20-b419-33c756c733d8.jpg
                    break;
                case 0x03:
                    if (recommendActBeans.size() > 3) {
                        recommendActBeans = recommendActBeans.subList(0, 2);
                    }
                    if (recommendAdapter == null) {
                        recommendAdapter = new ActListAdapter(recommendActBeans);
                        lvRecommend.setAdapter(recommendAdapter);
                    } else {
                        if (recommendActBeans == recommendAdapter.getData()) return;
                        recommendAdapter.setData(recommendActBeans);
                    }
                    break;
            }
        }
    }

    class ActCommentAdapter extends PervasiveAdapter<ActCommentBean.RowsBean> {

        public ActCommentAdapter(List<ActCommentBean.RowsBean> data) {
            super(data);
        }

        @Override
        protected void setUI(ViewHolder holder, int position, Context context) {
            ImageView img = (ImageView) holder.getItemView(R.id.img);
            TextView title = (TextView) holder.getItemView(R.id.title);
            TextView subtitle = (TextView) holder.getItemView(R.id.subtitle);
            TextView content = (TextView) holder.getItemView(R.id.content);
            content.setTextSize(16);

            String[] cutUrl = commentBeans.get(position).getAvatar().split("/");
            if (cutUrl.length >= 2){
                if (cutUrl[1].equals("profile")){
                    Glide.with(context).load(ApiConfig.BASE_AVATER + commentBeans.get(position).getAvatar()).transform(new CircleCrop()).into(img);
                }else if (cutUrl[1].equals("prod-api")){
                    Glide.with(ActDetailsActivity.this).load(ApiConfig.BASE_URL + commentBeans.get(position).getAvatar()).transform(new CircleCrop()).into(img);
                }else {
                    Glide.with(ActDetailsActivity.this).load(ApiConfig.BASE_URL + commentBeans.get(position).getAvatar()).transform(new CircleCrop()).into(img);
                }
            }else {
                Glide.with(context).load(R.mipmap.ic_launcher_round).transform(new CircleCrop()).into(img);
            }
            title.setText(commentBeans.get(position).getNickName());
            subtitle.setText("智慧ID：" + commentBeans.get(position).getUserId());
            content.setText(commentBeans.get(position).getContent());
        }

        @Override
        protected int getLayoutId() {
            return R.layout.common_list_item;
        }
    }

    class ActListAdapter extends PervasiveAdapter<ActListBean.RowsBean> {

        public ActListAdapter(List<ActListBean.RowsBean> data) {
            super(data);
        }

        @Override
        protected void setUI(ViewHolder holder, int position, Context context) {
            ImageView img = (ImageView) holder.getItemView(R.id.img);
            TextView title = (TextView) holder.getItemView(R.id.title);
            TextView subtitle = (TextView) holder.getItemView(R.id.subtitle);
            TextView content = (TextView) holder.getItemView(R.id.content);

            Glide.with(ActDetailsActivity.this)
                    .load(ApiConfig.BASE_URL + recommendActBeans.get(position).getImgUrl())
                    .into(img);
            title.setText(recommendActBeans.get(position).getName());
            subtitle.setText("报名人数：" + recommendActBeans.get(position).getSignupNum());
            content.setText("点赞数：" + recommendActBeans.get(position).getLikeNum());
        }

        @Override
        protected int getLayoutId() {
            return R.layout.common_list_item;
        }
    }
}